<template>
  <div class="login-box" v-show="showLogin">
    <div class="title">
      <div class="logo">
        <img :src="appLogo" v-if="appLogo" />
        <img src="../../../assets/img/register/logo.png" v-else alt />
        <h5>{{ appName || 'AW大师'}}</h5>
      </div>
      <div class="sub">
        <p>全景看房 - AI拓客 - 裂变传播 - 监控意向</p>
        <p>连接客户更简单</p>
      </div>
    </div>
    <div class="login-step" v-show="oldUser">
      <div class="login-cnt">
        <div class="phone">
          <span class="phone-code" @click="seclectCode">
            {{phoneCode}}
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-xialajiantou" />
            </svg>
          </span>
          <input
            type="tel"
            placeholder="请输入手机号码"
            oninput="value=value.replace(/[^0-9]/g,'')"
            maxlength="11"
            v-model.trim="mobile"
            @blur="blur"
          />
        </div>
        <div class="code">
          <input
            type="tel"
            placeholder="请输入验证码"
            oninput="value=value.replace(/[^0-9]/g,'')"
            maxlength="6"
            v-model.trim="verificationCode"
            @blur="blur"
          />
          <div
            class="send-code"
            :class="{'disabled': disabledBtn}"
            @click="sendCode"
          >{{sendCodeText}}</div>
        </div>
      </div>
      <div class="action-btn" :class="{'disabled': !registDisabled}" @click="nextHandler">确定</div>
      <van-actionsheet
        v-model="phoneShow"
        :actions="actions"
        cancel-text="取消"
        @select="onSelect"
        @cancel="onCancel"
      />
    </div>
    <!-- <div class="qrcode-step" v-show="!oldUser">
      <img :src="qrcodeImg" alt />
      <p>长按关注企业微信，进入使用</p>
    </div>-->
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import RegisterService from 'SERVICE/registService'
export default {
  data() {
    return {
      enterpriseId: '',
      uuid: '',
      officialAccountOpenId: '',
      mobile: '',
      verificationCode: '',
      phoneShow: false,
      actions: [
        { name: '中国大陆 +86', phoneCode: '+86' },
        { name: '香港 +852', phoneCode: '+852' }
      ],
      phoneCode: '+86',
      sendCodeText: '获取验证码',
      disabledBtn: true,
      codeTime: 60,
      registStatus: false,
      qrcodeImg: '',
      oldUser: true,
      showLogin: false,
      redPacketAmount: '',
      toPath: '',
      appName: '',
      appLogo: ''
    }
  },
  async created() {
    this.enterpriseId = this.$route.query.enterpriseId || localStorage.getItem('enterpriseId') || ''
    this.uuid = this.$route.query.uuid || localStorage.getItem('uuid') || ''
    this.officialAccountOpenId = this.$route.query.officialAccountOpenId || sessionStorage.getItem('officialAccountOpenId') || ''
    this.redPacketAmount = this.$route.query.redPacketAmount || ''
    this.toPath = this.$route.query.toPath || ''
    localStorage.setItem('enterpriseId', this.enterpriseId)
    localStorage.setItem('uuid', this.uuid)
    // 未登录获取sass 名称logo
    this.appName = this.userInfo.appName || localStorage.getItem('appName')
    this.appLogo = this.userInfo.appLogo || localStorage.getItem('appLogo')
    // 缓存过用户信息直接登录
    if (this.$route.query.appid) {
      let appid = this.$route.query.appid
      let key = `awMasterUserInfo_sass_${appid}`
      let data = localStorage.getItem(key)
      if (data) {
        // 更新用户信息
        let userInfo = JSON.parse(data)
        await this.$store.dispatch('getUserInfo', userInfo)
        // 签名
        try {
          window.awHelper.wechatHelper.init()
        } catch (e) {
          console.log('[error:window.awHelper.wechatHelper]')
        }
        // 跳转首页
        this.$router.push('/')
      } else {
        this.showLogin = true
      }
    } else {
      this.showLogin = true
    }
    // this.getQrcode()
  },
  watch: {
    mobile() {
      if (this.checkPhone()) {
        this.disabledBtn = false
      } else {
        this.disabledBtn = true
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    registDisabled() {
      return this.checkPhone() && this.verificationCode.length
    }
  },
  methods: {
    // 获取企业微信二维码
    // getQrcode() {
    //   let enterpriseId = this.enterpriseId
    //   RegisterService.queryByRegister(enterpriseId)
    //     .then(res => {
    //       this.qrcodeImg = res.qrCode
    //     })
    //     .catch()
    // },
    // 检测电话号码
    checkPhone() {
      let reg = /^1[3-9]\d{9}$/g
      let checkMobile = (this.phoneCode == '+86' && reg.test(this.mobile)) || (this.phoneCode == '+852' && this.mobile.length === 8)
      return checkMobile
    },
    // 显示区号选择弹框
    seclectCode() {
      this.phoneShow = true
    },
    // 选择区号
    onSelect(item) {
      this.phoneCode = item.phoneCode
      this.phoneShow = false
      this.disabledBtn = !this.checkPhone()
    },
    // 取消选择区号
    onCancel() {
      this.phoneShow = false
    },
    // 发送验证码
    sendCode() {
      if (!this.disabledBtn) {
        this.disabledBtn = true
        const result = RegisterService.sendMsgRegister({ mobile: this.mobile, areaCode: this.phoneCode, enterpriseId: this.enterpriseId })
        this.countDown()
      } else {
        if (this.sendCodeText.includes('重新发送')) {
          this.$toast('验证码发送过于频繁')
        } else {
          this.$toast('手机号码不正确，请检查')
        }
      }
    },
    // 验证码倒计时
    countDown() {
      this.sendCodeText = '重新发送(' + this.codeTime + 's)'
      let timer = setInterval(() => {
        this.codeTime--
        this.sendCodeText = '重新发送(' + this.codeTime + 's)'
        if (this.codeTime < 0) {
          clearInterval(timer)
          this.sendCodeText = '获取验证码'
          this.codeTime = 60
          this.disabledBtn = false
        }
      }, 1000)
    },
    // 检测表单
    nextHandler() {
      // 防止重复提交
      if (this.registStatus) {
        return false
      }
      // 检测字段
      if (this.mobile.length == 0) {
        return this.$toast('请输入手机号码')
      }
      if (!this.checkPhone()) {
        return this.$toast('手机号不正确，请重新输入')
      }
      if (this.verificationCode.length == 0) {
        return this.$toast('请输入验证码')
      }
      this.registStatus = true
      this.login()
    },
    // 登录
    login() {
      let parm = {
        areaCode: this.phoneCode,
        mobile: this.mobile,
        verificationCode: this.verificationCode,
        uuid: this.uuid,
        enterpriseId: this.enterpriseId,
        officialAccountOpenId: this.officialAccountOpenId
      }
      if (this.redPacketAmount) {
        parm.redPacketAmount = this.redPacketAmount
      }
      RegisterService.getUserInfoByCode(parm)
        .then(async res => {
          let userInfo = res.userInfo
          userInfo.userLoginType = res.userLoginType
          userInfo.cropId = this.$route.query.appid || localStorage.getItem('cropId')
          userInfo.articleShareFlag = res.articleShareFlag || '0'
          userInfo.token = res.token
          userInfo.jumpToDynamicDetail = res.jumpToDynamicDetail
          userInfo.selfSupport = res.selfSupport
          userInfo.articleAppId = res.articleAppId
          userInfo.appName = res.appName
          userInfo.appLogo = res.appLogo
          userInfo.belong = res.belong
          userInfo.belongType = res.belongType
          userInfo.uuid = res.uuid
          await this.$store.dispatch('getUserInfo', userInfo)
          if (this.toPath) {
            this.$router.push(this.toPath)
          } else {
            this.$router.push('/')
          }
        })
        .catch(() => {
          this.registStatus = false
        })
    },
    // 键盘遮挡
    blur() {
      setTimeout(() => {
        document.activeElement.scrollIntoViewIfNeeded(true)
        window.scroll(0, 0)
      }, 100)
    },
    // 后退
    goBack() {
      // 后退关闭公众号页面
      WeixinJSBridge.call('closeWindow')
    }
  },
  mounted() {
    window.addEventListener('popstate', this.goBack, false)
  },
  beforeDestroy() {
    window.removeEventListener('popstate', this.goBack, false)
  }
}
</script>


<style lang="less" scoped>
.login-box {
  font-size: 14px;
  color: #13284d;
  padding: 30px 24px;
  .title {
    .logo {
      display: flex;
      img {
        width: 36px;
        height: 36px;
        margin-right: 12px;
      }
      h5 {
        font-size: 32px;
        font-weight: 500;
        color: rgba(19, 40, 77, 1);
      }
    }
    .sub {
      margin-top: 8px;
      p {
        height: 20px;
        font-size: 14px;
        font-weight: 400;
        color: rgba(19, 40, 77, 1);
        line-height: 20px;
      }
    }
  }
  .login-cnt {
    padding-top: 20px;
    .phone {
      display: flex;
      align-items: center;
      color: #13284d;
      font-size: 16px;
      padding-left: 10px;
      .phone-code {
        flex-basis: 70px;
      }
      .icon {
        width: 12px;
        height: 12px;
        margin-left: 5px;
      }
    }
    .phone,
    .code {
      height: 48px;
      margin-top: 20px;
      font-size: 16px;
      color: #13284d;
      background: rgba(156, 165, 181, 0.2);
      display: flex;
      align-items: center;
      border-radius: 4px;
      input {
        flex: 1;
        border: none;
        padding: 0 10px;
        background-color: transparent;
        max-width: 220px;
        &::placeholder {
          padding-top: 0.12rem;
          color: #9ca5b5;
        }
      }
    }
    .code {
      .send-code {
        flex-basis: 120px;
        font-size: 14px;
        text-align: center;
        border-left: 1px solid rgba(19, 40, 77, 0.4);
        &.disabled {
          color: #9ca5b5;
        }
      }
    }
  }
  .action-btn {
    margin: 32px 0;
    height: 48px;
    background: rgba(0, 122, 230, 1);
    border-radius: 4px;
    font-size: 16px;
    color: rgba(255, 255, 255, 1);
    text-align: center;
    line-height: 48px;
    &.disabled {
      opacity: 0.4;
    }
  }
  .qrcode-step {
    text-align: center;
    margin-top: 24px;
    img {
      width: 200px;
      height: 200px;
    }
    p {
      color: #999;
    }
  }
}
</style>